
#include "Block.h"
#include "my_def.h"
#include "string_util.h"

CBlock::CBlock()
	:m_nBlockType(0)
	,m_pImage(NULL)
	,m_nPreZorder(0)
	,m_bDoingAction(false)
{
}

CBlock::~CBlock()
{
}

CBlock* CBlock::blockWithType(int nType)
{
	CBlock* pBlock = new CBlock();
	pBlock->autorelease();
	pBlock->SetBlockType(nType);

	return pBlock;
}

int CBlock::GetBlockType()
{
	return m_nBlockType;
}

void CBlock::SetBlockType(int nType)
{
	m_nBlockType = nType;

	std::string strFileName;
	STRING_UTIL::Format(strFileName, "image/blocks/block_n_%d.png",m_nBlockType);

	CCTexture2D* pBlockTex = CCTextureCache::sharedTextureCache()->addImage(strFileName.c_str());

	if(m_pImage == NULL)
	{
		m_pImage = CCSprite::spriteWithTexture( pBlockTex );
		m_pImage->setAnchorPoint(ccp(0.5f,0.5f));
		m_pImage->setPosition(CCPointZero);
		addChild(m_pImage);
	}
	else
	{
		m_pImage->setRotation(0);
		m_pImage->setTexture(pBlockTex);
	}

	if(nType == E_BLOCK_BAR)
	{
		m_nBlockOrient[0] = E_TOP;
		m_nBlockOrient[1] = E_BOTTOM;
	}
	else if(nType == E_BLOCK_CORNER)
	{
		m_nBlockOrient[0] = E_TOP;
		m_nBlockOrient[1] = E_RIGHT;
	}
	else if(nType == E_BLOCK_TBAR)
	{
		m_nBlockOrient[0] = E_RIGHT;
		m_nBlockOrient[1] = E_BOTTOM;
		m_nBlockOrient[2] = E_LEFT;
	}
	else if(nType == E_BLOCK_TBAR)
	{
		m_nBlockOrient[0] = E_TOP;
		m_nBlockOrient[1] = E_RIGHT;
		m_nBlockOrient[2] = E_BOTTOM;
		m_nBlockOrient[3] = E_LEFT;
	}
}

void CBlock::BlockRotate()
{
	//startAction();

	//this->stopAllActions();

	float fAngle = getRotation();

	fAngle = (((int)fAngle/90)+1)*90;

	CCRotateTo* pRotate = CCRotateTo::actionWithDuration(0.06f,fAngle);

	this->runAction( CCSequence::actions( pRotate, CCCallFunc::actionWithTarget(this, callfunc_selector(CBlock::doneAction)),NULL));
}

void CBlock::BlockFlyTo(CCPoint pt)
{
	startAction();

	this->stopAllActions();

	CCJumpTo* pJump = CCJumpTo::actionWithDuration(0.1f, pt, 20.0f, 1);

	this->runAction( CCSequence::actions( pJump, CCCallFunc::actionWithTarget(this, callfunc_selector(CBlock::doneAction)),NULL));
}

void CBlock::startAction()
{
	m_bDoingAction = true;
}

void CBlock::doneAction()
{
	resetOrient();
	m_bDoingAction = false;
}

bool CBlock::isDoing()
{
	return m_bDoingAction;
}

void CBlock::resetOrient()
{
	float fAngle = getRotation();

	int nOrient = (int)fAngle/90;

	int nWayCounter = 0;
	switch( m_nBlockType )
	{
	case E_BLOCK_BAR:
		nWayCounter = 2;
		break;

	case E_BLOCK_CORNER:
		nWayCounter = 2;
		break;

	case E_BLOCK_TBAR:
		nWayCounter = 3;
		break;

	case E_BLOCK_CROSS:
		nWayCounter = 4;
		break;
	}

	for(int i=0; i<nWayCounter; i++)
	{
		int nVal = ++m_nBlockOrient[i];
		overrangeCheck(nVal, E_ERROR_ORIENT-1, E_TOP);
		m_nBlockOrient[i] = nVal;
	}
}

void CBlock::overrangeCheck(int& nVal, int nMax, int nDefaultVal)
{
	if( nMax < nVal )
		nVal = nDefaultVal;
}